import md5 from './md5'
import store from "../store"
import Vue from 'vue'
import qs from 'qs'

export default ($wx) => {
	const METHODS = ['get', 'post', 'put', 'delete']
	
	// zurl = "http://192.168.0.74/Api";
	let publicdata = {
		sign: md5(Date.parse(new Date()) / 1000 + "2y92rfa969y4hyjrwuqjygog3zcu50l3"),
		timestamp: String(Date.parse(new Date()) / 1000),
	}
	let needtoken = {
		token: wx.getStorageSync("user_token"),
		// user_id:  wx.getStorageSync("user_id")
	}
	let handler = {
		get(target, property) {
			METHODS.forEach(method => {
				target[method] = (url, ndata, needt) => {
					return new Promise((resolve, reject) => {
						wx.showLoading();
						if (needt == true) {
							$wx.request({
								url: url,
								header: {
									"Content-Type": "application/x-www-form-urlencoded",
									"Authorization": publicdata.sign + " " + publicdata.timestamp + " " + (needtoken.token || "")
								},
								method: method.toLocaleUpperCase(),
								data: qs.stringify(ndata),
								success: res => {
									console.log(res);
									wx.hideLoading();
									if (res.data.status != 0) {
										wx.showToast({
											title: res.data.msg,
											icon: "none"
										});
										if (res.data.status == 10003 || res.data.status == 10001 || res.data.status == 10004) {

										}
									}
									else {
										// wx.showToast({
										// 	title: res.data.msg,
										// 	icon: "none"
										// });
										resolve(res.data);
									}
								},
								fail: error => {
									console.log(error);
									reject(error);
									wx.showToast({
										title: "接口请求失败",
										icon: "none"
									});
									wx.hideLoading();
								}
							})
						}
						else {
							$wx.request({
								url: zurl + url,
								header: {
									"Content-Type": "application/x-www-form-urlencoded",
									"Authorization": publicdata.sign + " " + publicdata.timestamp + " " + (needtoken.token || "")
								},
								method: method.toLocaleUpperCase(),
								data: qs.stringify(ndata),
								success: res => {
									console.log(res);
									wx.hideLoading();
									if (res.data.status != 0) {
										wx.showToast({
											title: res.data.msg,
											icon: "none"
										});
										if (res.data.status == 10003 || res.data.status == 10001 || res.data.status == 10004) {

										}
									}
									else {
										// wx.showToast({
										// 	title: res.data.msg,
										// 	icon: "none"
										// });
										resolve(res.data);

									}
								},
								fail: error => {
									reject(error);
									wx.hideLoading();
								}
							})
						}
					})
				}
			})
			return target[property]
		}
	}

	const API = new Proxy({}, handler)
	return API
}

export function formatUrl(){
	var defUrl = store.state.loginPeriodName;
	if(!defUrl || defUrl == ""){
		return 'https://m1.maoqio.com/Api';
	}else{
		return defUrl;
	}
}